package com.platform.api;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Prop;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

import static com.platform.config.Constants.EXTENDED_DAYS;
import static com.platform.util.CommonUtil.getProp;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends ApiBaseAction {


    static Prop prop = getProp();
    String appid = prop.get("payAppId");
    String partner = prop.get("payMchId");
    String paternerKey = prop.get("payPaternerKey");
    String refund_url = prop.get("payCallBackDomain") + "/api/pay/refund_notify";
    String certPath = ResourceUtil.getConfigByName("wx.certName");

    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private ApiOrderGoodsService orderGoodsService;
    @Autowired
    private ApiKdniaoService apiKdniaoService;
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiSysMacroService macroService;
    @Autowired
    private ApiInvoiceService apiInvoiceService;
    @Autowired
    private ApiOrderCommentPictureService apiOrderCommentPictureService;
    @Autowired
    private ApiOrderCommentService apiOrderCommentService;
    @Autowired
    private ApiGoodsService apiGoodsService;
    @Autowired
    private ApiProductService apiProductService;
    @Autowired
    private ApiOrderRefundPictureService apiOrderRefundPictureService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiCouponService apiCouponService;

    /**
     * 取消退款
     *
     * @param loginUser
     * @param orderId
     * @return
     */
    @RequestMapping("cancleRefund")
    public Object cancleRefund(@LoginUser UserVo loginUser, Integer orderId) {
        OrderVo orderInfo = orderService.queryById(orderId);
        //判断订单是否存在
        if (null == orderInfo) {
            return toResponsFail("订单不存在");
        }
        //判断订单是否当前用户
        Long userId = orderInfo.getUser_id();
        if (!loginUser.getUserId().equals(userId)) {
            return toResponsFail("该订单不属于当前用户");
        }

        Integer orderStatus = orderInfo.getOrder_status();

        if (!(orderStatus == 401 || orderStatus == 402)) {
            return toResponsFail("当前订单不是退款状态");
        }

        String shippingNo = orderInfo.getShipping_no();

        orderInfo.setOrder_status(201);
        if (shippingNo != null) {
            orderInfo.setOrder_status(300);
        }

        orderService.update(orderInfo);

        return toResponsSuccess("取消成功");
    }


    /**
     * 申请退款
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("applyRefund")
    public Object applyRefund(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String orderId = jsonParam.getString("orderId");
        if (!Validator.isNumber(orderId)) {
            return toResponsFail("请提交正确的订单id");
        }
        String refundType = jsonParam.getString("refundType");
        if (!Validator.isNumber(refundType)) {
            return toResponsFail("请提交正确的退款类型");
        }
        String goodsStatus = jsonParam.getString("goodsStatus");
        if (!Validator.isNumber(goodsStatus)) {
            return toResponsFail("请提交正确的货物状态");
        }
        String refundReason = jsonParam.getString("refundReason");
        if (refundReason.length() > 500) {
            return toResponsFail("退款理由不能超过500字");
        }
        String refundAmount = jsonParam.getString("refundAmount");
        if (!Validator.isNumber(refundAmount)) {
            return toResponsFail("请提交正确的退款金额");
        }
        String refundRemark = jsonParam.getString("refundRemark");
        if (refundRemark.length() > 500) {
            return toResponsFail("退款说明不能超过500字");
        }
        JSONArray imagesList = jsonParam.getJSONArray("imgList");
        if (imagesList != null && imagesList.size() > 9) {
            return toResponsFail("图片不能超过9张");
        }
        Integer orderIdInteger = Integer.valueOf(orderId);
        OrderVo orderVo = orderService.queryObject(orderIdInteger);
        if (orderVo == null) {
            return toResponsFail("该订单不存在！");
        }

        BigDecimal refundAmountBigDecimal = new BigDecimal(refundAmount);
        if (refundAmountBigDecimal.compareTo(orderVo.getActual_price()) > 0) {
            return toResponsFail("退款金额不能超过订单总价！");
        }

        Long userId = orderVo.getUser_id();
        if (!userId.equals(loginUser.getUserId())) {
            return toResponsFail("该订单不属于当前用户");
        }

        Integer refundTypeInteger = Integer.valueOf(refundType);
        orderVo.setRefundType(refundTypeInteger);
        orderVo.setOrder_status(401);
        if (refundTypeInteger == 2) {
            orderVo.setOrder_status(402);
            //发货状态 商品配送情况;0未发货,1已发货,2已收货,4退货
            if (orderVo.getOrder_status() == 0) {
                return toResponsFail("当前订单没发货,请重新填写");
            }
            orderVo.setShipping_status(4);
        }
        orderVo.setGoodsStatus(Integer.valueOf(goodsStatus));
        orderVo.setRefundReason(refundReason);
        orderVo.setRefundAmount(refundAmountBigDecimal);
        orderVo.setRefundApplyTime(new Date());
        orderVo.setPay_status(4);
        orderService.update(orderVo);

        if (null != imagesList && imagesList.size() > 0) {
            int i = 0;
            for (Object imgLink : imagesList) {
                i++;
                OrderRefundPictureVo vo = new OrderRefundPictureVo();
                vo.setOrderId(orderIdInteger);
                vo.setPicUrl(imgLink.toString());
                vo.setSortOrder(i);
                apiOrderRefundPictureService.save(vo);
            }
        }


        return toResponsSuccess("已成功申请");
    }


    /**
     * @param refundType 退款类型：1-仅退款；2-退货退款
     * @return
     */
    @IgnoreAuth
    @RequestMapping("getRefundReasonList")
    public Object getRefundReasonList(@RequestParam(value = "refundType", defaultValue = "1") Integer refundType) {

        Map<String, Object> params = new HashMap<>(3);
        params.put("parent_id", 31);
        if (refundType == 2) {
            params.put("parent_id", 24);
        }
        params.put("status", 1);
        params.put("sidx", "order_num");
        params.put("order", "desc");
        List<SysMacroVo> sysMacroVos = macroService.queryList(params);
        return toResponsSuccess(sysMacroVos);
    }


    /**
     * 删除订单
     */
    @RequestMapping("deleteOrder")
    public Object delete(@LoginUser UserVo loginUser, @RequestParam Integer orderId) {
        OrderVo orderInfo = orderService.queryById(orderId);
        //判断订单是否存在
        if (null == orderInfo) {
            return toResponsFail("订单不存在");
        }
        //判断订单是否当前用户
        Long user_id = orderInfo.getUser_id();
        if (!loginUser.getUserId().equals(user_id)) {
            return toResponsFail("该订单不属于当前用户");
        }
        Integer order_status = orderInfo.getOrder_status();
        System.out.println("orderStatus" + order_status);
        //判断订单状态
        if (!(order_status == 101 || order_status == 401)) {
            return toResponsFail("订单未完成，不能删除");
        }

        //假删除
        orderInfo.setIs_delete(1);
        orderService.update(orderInfo);
        //真删除
//        //删除订单绑定的商品
//        orderGoodsService.deleteByOrderId(orderId);
//        //删除订单
//        orderService.delete(orderId);

        return toResponsSuccess("删除成功");
    }


    /**
     * 获取订单列表
     */
    @RequestMapping("list")
    public Object list(@LoginUser UserVo loginUser,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size,
                       Integer orderStatus) {

        Long userId = loginUser.getUserId();

        //处理超时未支付订单
        orderService.updateTimeOutOrder(userId);

        //更新需要确认收货的订单
        orderService.updateConfirmOrder(userId);

        //查询列表数据
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        params.put("orderStatus", orderStatus);
        params.put("is_delete", 0);
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "desc");

        Query query = new Query(params);
        List<OrderVo> orderEntityList = orderService.queryList(query);

        int total = orderService.queryTotal(query);

        ApiPageUtils pageUtil = new ApiPageUtils(orderEntityList, total, query.getLimit(), query.getPage());
        //
        for (OrderVo item : orderEntityList) {
            Map<String, Object> orderGoodsParam = new HashMap<>();
            orderGoodsParam.put("order_id", item.getId());
            //订单的商品
            List<OrderGoodsVo> goodsList = orderGoodsService.queryList(orderGoodsParam);
            Integer goodsCount = 0;
            for (OrderGoodsVo orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
                item.setGoodsCount(goodsCount);
            }
            item.setOrderGoodsList(goodsList);
        }
        return toResponsSuccess(pageUtil);
    }

    /**
     * 获取订单详情
     */
    @RequestMapping("detail")
    public Object detail(@LoginUser UserVo loginUser, @RequestParam Integer orderId) {
        Map<String, Object> resultObj = new HashMap<>();
        //
        OrderVo orderInfo = orderService.queryObject(orderId);
        if (null == orderInfo) {
            return toResponsFail("订单不存在");
        }
        //判断订单是否当前用户
        Long user_id = orderInfo.getUser_id();
        if (!loginUser.getUserId().equals(user_id)) {
            return toResponsFail("该订单不属于当前用户");
        }
        Map<String, Object> orderGoodsParam = new HashMap<>();
        orderGoodsParam.put("order_id", orderId);
        //订单的商品
        List<OrderGoodsVo> orderGoods = orderGoodsService.queryList(orderGoodsParam);

        //订单可操作的选择,删除，支付，收货，评论，退换货
        Map handleOption = orderInfo.getHandleOption();
        //
        resultObj.put("orderInfo", orderInfo);
        resultObj.put("orderGoods", orderGoods);
        resultObj.put("handleOption", handleOption);
        List Traces = new ArrayList();


        if (orderInfo.getShipping_id() != null && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
            // 快递
            Traces = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
            //倒序
            //Collections.reverse(Traces);
        }
        resultObj.put("shippingList", Traces);

        return toResponsSuccess(resultObj);
    }

    /**
     * 保存订单
     */
    @RequestMapping("submit")
    public Object submit(@LoginUser UserVo loginUser,
                         Integer couponId,//优惠券id
                         String couponNumber,//优惠券数量
                         String postscript,//留言
                         @RequestParam("addressId") Integer addressId,//地址id
                         BigDecimal fullCutCouponDec,
                         @RequestParam("isBilling") Integer isBilling,//是否开票：1-是；0-否
                         Integer invoiceId) {//发票Id

        if (Validator.isEmpty(postscript)) {
            postscript = "";
        }

        //检验发票信息
        if (isBilling == 1) {
            InvoiceVo invoiceVo = apiInvoiceService.queryDefaultObject(loginUser.getUserId());
            if (invoiceVo == null) {
                return toResponsFail("发票信息不正确");
            }
            Integer userId = invoiceVo.getUserId();
            if (userId != loginUser.getUserId().intValue()) {
                return toResponsFail("发票信息与账号不符");
            }
        }


        Map resultObj = null;
        try {
            resultObj = orderService.submit(loginUser, couponId, couponNumber, postscript, addressId, fullCutCouponDec, isBilling, invoiceId);
            if (null != resultObj) {
                return toResponsObject(MapUtils.getInteger(resultObj, "errno"), MapUtils.getString(resultObj, "errmsg"), resultObj.get("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 取消订单
     */
    @RequestMapping("cancelOrder")
    public Object cancelOrder(@LoginUser UserVo loginUser, @RequestParam Integer orderId) {
        try {
            OrderVo orderVo = orderService.queryById(orderId);
            //判断订单是否存在
            if (orderVo == null) {
                return toResponsFail("订单不存在");
            }
            //判断订单是否当前用户
            Long user_id = orderVo.getUser_id();
            if (!loginUser.getUserId().equals(user_id)) {
                return toResponsFail("该订单不属于当前用户");
            }
            //判断订单状态
//            if (orderVo.getOrder_status() == 300) {
//                return toResponsFail("已发货，不能取消");
//            } else if (orderVo.getOrder_status() == 301) {
//                return toResponsFail("已收货，不能取消");
//            }
            if (orderVo.getOrder_status() != 0) {
                return toResponsFail("仅未支付的订单可取消");
            }

            Map<String, Object> orderGoodsParam = new HashMap<>();
            orderGoodsParam.put("order_id", orderId);
            List<OrderGoodsVo> orderGoodsVoList = orderGoodsService.queryList(orderGoodsParam);
            if (orderGoodsVoList.size() > 0) {
                for (OrderGoodsVo orderGoodsVo : orderGoodsVoList) {
                    Integer goodsId = orderGoodsVo.getGoods_id();
                    GoodsVo goodsVo = apiGoodsService.queryObject(goodsId);
                    //取消会员身份
                    Integer isMemberLimit = goodsVo.getIsMemberLimit();
                    if (isMemberLimit != null && isMemberLimit == 1) {
                        apiUserService.updateUserMember(orderVo.getUser_id(), 0);
                    }
                }
            }

            // 已经支付，需要退款
            if (orderVo.getPay_status() == 2) {
//                BigDecimal actual_price = orderVo.getActual_price();
//                Map<String, String> params = new HashMap<>();
//                //公众账号ID
//                params.put("appid", appid);
//                //商户号
//                params.put("mch_id", partner);
//                params.put("out_trade_no", orderVo.getOut_trade_no());
//                //商户订单号
//                params.put("out_refund_no", System.currentTimeMillis() + "");
//                //订单金额
//                params.put("total_fee", String.valueOf((((int) (orderVo.getActual_price().floatValue() * 100)))));
//                //退款金额
//                params.put("refund_fee", String.valueOf((((int) (orderVo.getActual_price().floatValue() * 100)))));
//                //退款结果通知url
//                params.put("notify_url", refund_url);
//                Map<String, String> refund = PaymentApi.refund(params, paternerKey, certPath);
//
//                System.out.println("refund:" + refund);
//                String resultCode = refund.get("result_code");
//
//                if (resultCode == null) {
//                    return toResponsFail("系统错误，请联系管理员");
//                }
//
//                if ("FAIL".equals(resultCode)) {
//                    return toResponsFail(refund.get("err_code_des"));
//                }
//                /*
//                订单状态
//                1xx 表示订单取消和删除等状态 0订单创建成功等待付款，　101订单已取消，　102订单已删除
//                2xx 表示订单支付状态　201订单已付款，等待发货
//                3xx 表示订单物流相关状态　300订单已发货， 301用户确认收货
//                4xx 表示订单退换货相关的状态　401 没有发货，退款　402 已收货，退款退货
//                */
//                orderVo.setOrder_status(401);
//                //付款状态 支付状态;0未付款;1付款中;2已付款;4退款
//                orderVo.setPay_status(4);
//                orderService.update(orderVo);
//                return toResponsSuccess("退款成功");
            } else {
                //101-订单已取消
                orderVo.setOrder_status(101);
                orderService.update(orderVo);
                return toResponsSuccess("取消成功");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 确认收货
     */
    @RequestMapping("confirmOrder")
    public Object confirmOrder(@LoginUser UserVo loginUser, @RequestParam Integer orderId) {
        try {
            OrderVo orderVo = orderService.queryById(orderId);
            //判断订单是否存在
            if (orderVo == null) {
                return toResponsFail("订单不存在");
            }
            //判断订单是否当前用户
            Long user_id = orderVo.getUser_id();
            if (!loginUser.getUserId().equals(user_id)) {
                return toResponsFail("该订单不属于当前用户");
            }
            //判断订单是否已经发货
            if (orderVo.getOrder_status() != 300) {
                return toResponsFail("订单没发货,不可确认收货");
            }
            //正常情况下
            orderVo.setOrder_status(301);//301-用户确认收货
            orderVo.setShipping_status(2);//0-未发货；1-已发货；2-已经收货；4-退货
            orderVo.setConfirm_time(new Date());//确认收货时间
            orderService.update(orderVo);
            return toResponsSuccess("确认收货成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 延时收货
     */
    @RequestMapping("delayOrder")
    public Object delayOrder(@LoginUser UserVo loginUser, @RequestParam Integer orderId) {
        try {
            OrderVo orderVo = orderService.queryById(orderId);
            //判断订单是否存在
            if (orderVo == null) {
                return toResponsFail("订单不存在");
            }
            //判断订单是否当前用户
            Long user_id = orderVo.getUser_id();
            if (!loginUser.getUserId().equals(user_id)) {
                return toResponsFail("该订单不属于当前用户");
            }
            //判断订单是否已经发货
            if (orderVo.getOrder_status() != 300) {
                return toResponsFail("订单没发货,不可延时确认收货");
            }
            //正常情况下
            orderVo.setIs_delay(1);

            Integer extendedDays = EXTENDED_DAYS;
            SysMacroVo macroVo1 = macroService.queryObject((long) 11);//收货延长天数
            if (macroVo1 != null) {
                String value = macroVo1.getValue();
                if (Validator.isNumber(value)) {
                    extendedDays = Integer.valueOf(value);
                }
            }
            DateTime offset = DateUtil.offsetDay(new Date(), extendedDays);

            orderVo.setDelay_date(offset);
            orderService.update(orderVo);
            return toResponsSuccess("延时收货成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toResponsFail("提交失败");
    }

    /**
     * 个人中心的订单数量以及主要信息的返回
     */
    @RequestMapping("orderCount")
    public Object orderCount(@LoginUser UserVo loginUser) {
        Long userId = loginUser.getUserId();
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> params = new HashMap<>();

        params.put("user_id", userId);
        params.put("orderStatus", 0);
        data.put("dfk", orderService.queryTotal(params));

        params.put("orderStatus", 201);
        data.put("dfh", orderService.queryTotal(params));

        params.put("orderStatus", 301);
        data.put("dpl", orderService.queryTotal(params));

        params.put("orderStatus", 300);
        data.put("dsh", orderService.queryTotal(params));


        OrderVo orderInfo = orderService.queryNewestOrder(params);
        if (orderInfo != null) {
            Map<String, Object> orderGoodsParam = new HashMap<>();
            orderGoodsParam.put("order_id", orderInfo.getId());
            //订单的商品
            List<OrderGoodsVo> orderGoods = orderGoodsService.queryList(orderGoodsParam);
            orderInfo.setOrderGoodsList(orderGoods);

            if (!StringUtils.isEmpty(orderInfo.getShipping_code()) && !StringUtils.isEmpty(orderInfo.getShipping_no())) {
                // 快递
                List tracesList = apiKdniaoService.getOrderTracesByJson(orderInfo.getShipping_code(), orderInfo.getShipping_no());
                //Collections.reverse(tracesList);
                orderInfo.setTracesList(tracesList);

            }
        }


        data.put("orderInfo", orderInfo);

        return toResponsSuccess(data);
    }


    /**
     * @param loginUser
     * @param id
     * @param invoiceType    发票类型：1-电子发票；2-纸质发票
     * @param headerType     抬头类型：1-个人；2-单位
     * @param headerContent  发票抬头
     * @param invoicerMobile 是否默认：0-否;1-是
     * @param invoicerEmail  发票内容：1-商品明细；2-商品类别
     * @param isDefault      收票人手机号码
     * @param contentType    收票人邮箱
     * @return
     */
    @RequestMapping("saveOrUpdateInvoice")
    public Object saveOrUpdateInvoice(@LoginUser UserVo loginUser,
                                      Integer id,
                                      @RequestParam(value = "invoiceType", defaultValue = "1") Integer invoiceType,
                                      @RequestParam(value = "headerType", defaultValue = "1") Integer headerType,
                                      @RequestParam("headerContent") String headerContent,
                                      @RequestParam("invoicerMobile") String invoicerMobile,
                                      String invoicerEmail,
                                      String taxpayerIdentificationNumber,
                                      @RequestParam(value = "isDefault", defaultValue = "0") Integer isDefault,
                                      @RequestParam(value = "contentType", defaultValue = "1") Integer contentType) {

        InvoiceVo invoiceVo;
        Long userId = loginUser.getUserId();

        //常规校验
        if (invoiceType == 1) {
            if (!Validator.isEmail(invoicerEmail)) {
                return toResponsFail("请填写正确的收票人邮箱");
            }
        }
        if (headerType == 2) {
            if (!Validator.isNumber(taxpayerIdentificationNumber) || taxpayerIdentificationNumber.length() > 30) {
                return toResponsFail("请填写正确的纳税人识别号码");
            }
        }
        if (!Validator.isMobile(invoicerMobile)) {
            return toResponsFail("请填写正确的收票人手机号码");
        }
        if (headerContent.length() > 120) {
            return toResponsFail("发票抬头最长120个字符");
        }

        if (id == null) {//新增
            invoiceVo = new InvoiceVo();
            invoiceVo.setUserId(userId.intValue());
            invoiceVo.setInvoiceType(invoiceType);
            invoiceVo.setHeaderType(headerType);
            invoiceVo.setHeaderContent(headerContent);

            //清除之前设定默认的值
            if (isDefault == 1) {
                apiInvoiceService.updateIsDefault(userId);
            }

            invoiceVo.setIsDefault(isDefault);
            invoiceVo.setContentType(contentType);
            invoiceVo.setInvoicerMobile(invoicerMobile);
            if (invoiceType == 1) {
                invoiceVo.setInvoicerEmail(invoicerEmail);
            }
            if (headerType == 2) {
                invoiceVo.setTaxpayerIdentificationNumber(taxpayerIdentificationNumber);
            }
            invoiceVo.setAddTime(new Date());
            apiInvoiceService.save(invoiceVo);
            return toResponsSuccess(invoiceVo);
        }

        //修改
        invoiceVo = apiInvoiceService.queryObject(id);
        if (invoiceVo == null) {
            return toResponsFail("不存在该发票信息");
        }
        invoiceVo.setInvoiceType(invoiceType);
        invoiceVo.setHeaderType(headerType);
        invoiceVo.setHeaderContent(headerContent);
        //清除之前设定默认的值
        if (isDefault == 1) {
            apiInvoiceService.updateIsDefault(userId);
        }
        invoiceVo.setIsDefault(isDefault);
        invoiceVo.setContentType(contentType);
        invoiceVo.setInvoicerMobile(invoicerMobile);
        if (invoiceType == 1) {
            invoiceVo.setInvoicerEmail(invoicerEmail);
            invoiceVo.setTaxpayerIdentificationNumber(taxpayerIdentificationNumber);
        }
        if (headerType == 2) {
            invoiceVo.setTaxpayerIdentificationNumber(taxpayerIdentificationNumber);
        }
        apiInvoiceService.update(invoiceVo);

        return toResponsSuccess(invoiceVo);
    }

    @RequestMapping("queryInvoiceList")
    public Object queryInvoiceList(@LoginUser UserVo loginUser) {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", loginUser.getUserId());
        return toResponsSuccess(apiInvoiceService.queryList(params));
    }

    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("postComment")
    public Object postComment(@LoginUser UserVo loginUser) throws UnsupportedEncodingException {

        JSONObject jsonParam = getJsonRequest();

        if (Validator.isNull(jsonParam)) {
            return toResponsFail("请提供评论");
        }

        //订单id
        Integer orderId = jsonParam.getInteger("orderId");
        //快递包装
        Integer expressPackagingStar = jsonParam.getInteger("expressPackagingStar");
        //送货速度
        Integer deliverySpeedStar = jsonParam.getInteger("deliverySpeedStar");
        //配送员服务态度
        Integer staffAttitudeStar = jsonParam.getInteger("staffAttitudeStar");
        //是否匿名：1-是；0-否
        Integer isAnonymous = jsonParam.getInteger("isAnonymous");


        //todo 参数常规校验
        if (orderId == null) {
            return toResponsFail("请提供订单id");
        }
        if (expressPackagingStar == null) {
            return toResponsFail("请提供快递包装评分");
        }
        if (deliverySpeedStar == null) {
            return toResponsFail("请提供送货速度评分");
        }
        if (staffAttitudeStar == null) {
            return toResponsFail("请提供配送员服务态度评分");
        }
        if (isAnonymous == null) {
            return toResponsFail("请选择是否匿名");
        }

        //评论数组
        JSONArray commentList = jsonParam.getJSONArray("comment");

        if (commentList != null && commentList.size() > 0) {
            Integer allStar = 0;
            for (int i = 0; i < commentList.size(); i++) {
                JSONObject commentObj = commentList.getJSONObject(i);
                Integer goodId = commentObj.getInteger("goodId");
                Integer productId = commentObj.getInteger("productId");
                Integer star = commentObj.getInteger("star");
                String content = commentObj.getString("content");
                JSONArray imagesList = commentObj.getJSONArray("imagesList");

                allStar = allStar + star;

                //todo 参数常规校验
                if (goodId == null) {
                    return toResponsFail("请提供商品id");
                }
                if (productId == null) {
                    return toResponsFail("请提供产品id");
                }
                if (star == null) {
                    return toResponsFail("请提供星级评分");
                }
                if (content.length() > 1500) {
                    return toResponsFail("内容不能超过1500个字符");
                }
                if (imagesList != null && imagesList.size() > 9) {
                    return toResponsFail("图片不能超过9张");
                }
                //保存评论数据
                OrderCommentVo orderCommentVo = new OrderCommentVo();
                orderCommentVo.setOrderId(orderId);
                orderCommentVo.setGoodId(goodId);
                GoodsVo goodsVo = apiGoodsService.queryObject(goodId);
                if (goodsVo == null) {
                    return toResponsFail("商品不存在");
                }
                //处理星级
                goodsVo.setStar(Integer.valueOf((new BigDecimal(goodsVo.getStar()).add(new BigDecimal(star))).divide(new BigDecimal(2)).setScale(0, BigDecimal.ROUND_HALF_UP).toString()));
                orderCommentVo.setGoodName(goodsVo.getName());
                orderCommentVo.setStar(star);
                orderCommentVo.setProductId(productId);
                ProductVo productVo = apiProductService.queryObject(productId);
                if (productVo == null) {
                    return toResponsFail("产品不存在");
                }

                orderCommentVo.setProductName(productVo.getProduct_name());

                orderCommentVo.setContent(EmojiUtils.emojiConvert1(content));
                orderCommentVo.setStatus(1);
                orderCommentVo.setUserId(loginUser.getUserId().intValue());
                orderCommentVo.setAddTime(new Date());
                orderCommentVo.setIsAnonymous(isAnonymous);

                int insertId = apiOrderCommentService.save(orderCommentVo);


                if (insertId > 0 && null != imagesList && imagesList.size() > 0) {
                    int j = 0;
                    for (Object imgLink : imagesList) {
                        j++;
                        OrderCommentPictureVo pictureVo = new OrderCommentPictureVo();
                        pictureVo.setCommentId(orderCommentVo.getId());
                        pictureVo.setPicUrl(imgLink.toString());
                        pictureVo.setSortOrder(j);
                        apiOrderCommentPictureService.save(pictureVo);
                    }
                }
            }
            //判断是否全部好评
            if (allStar == commentList.size() * 5) {
                Map<String, Object> couponParam = new HashMap<>();
                couponParam.put("send_type", 6);
                CouponVo newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
                if (null != newCouponConfig) {
                    //只能领取一次
                    couponParam.remove("send_type");
                    couponParam.put("coupon_id", newCouponConfig.getId());
                    couponParam.put("user_id", loginUser.getUserId());
                    int total = apiUserCouponService.queryTotal(couponParam);
                    if (total == 0) {
                        UserCouponVo userCouponVo = new UserCouponVo();
                        userCouponVo.setAdd_time(new Date());
                        userCouponVo.setCoupon_id(newCouponConfig.getId());
                        userCouponVo.setCoupon_number(CharUtil.getRandomString(12));
                        userCouponVo.setUser_id(loginUser.getUserId());
                        apiUserCouponService.save(userCouponVo);
                    }
                }
            }
        }

        //todo 保存到订单数据里面
        OrderVo orderVo = orderService.queryById(orderId);
        orderVo.setExpress_packaging_star(expressPackagingStar);
        orderVo.setDelivery_speed_star(deliverySpeedStar);
        orderVo.setStaff_attitude_star(staffAttitudeStar);
        orderVo.setOrder_status(302);
        orderService.update(orderVo);

        return toResponsMsgSuccess("评论成功");
    }
}